<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        /* Testing */
        //        $data = array(
        //            'username' => 'jack',
        //            'userid' => '123',
        //            'is_logged_in' => TRUE,
        //            'user_type' => '1'
        //        );
        //
        //        $this->session->set_userdata($data);
        /* Testing */

        $_css = '<link href="' . base_url() . 'css/index.css" rel="stylesheet" type="text/css" />';
        $_title = 'File Search';

        $data['main_content'] = 'web_view';
        $data['h_data']['page_title'] = $_title;
        $data['h_data']['_css'] = $_css;
        $pass = $this->session->userdata('pass_cap');
        $islogin = $this->session->userdata('is_logged_in');
        $data['m_data']['islogin'] = (empty($islogin)) ? false : $islogin;
        $data['m_data']['pass_captcha'] = (empty($pass)) ? false : $pass;


        $this->load->view('includes/template', $data);
    }

    public function fetch_result()
    {
        $type = $this->uri->segment(3);
        $keyword = $this->uri->segment(4);
        $captcha = $this->session->userdata("pass_cap");
        $captcha = (empty($captcha)) ? false : $captcha;
        if (empty($type)) {
            die('Errors!');
        }
        $login = $this->session->userdata('is_logged_in');
        $row0 = null;
        $row1 = null;
        if ($type == '1') { //File search;
            if ($login) {
                $query = $this->db->query("SELECT * FROM `file_info` WHERE
                    (`file_keyword` like '%$keyword%' OR
                     `file_name` like '%$keyword%') AND
                    `file_approved` = '1'
                    ORDER BY `file_visted` DESC");
            } else {
                if ($captcha) {
                    $limiter = '';
                } else {
                    $limiter = 'LIMIT 3';
                }
                //                echo "SELECT * FROM `file_info` WHERE
                //                    (`file_keyword` like '%$keyword%' OR
                //                     `file_name` like '%$keyword%') AND
                //                    `file_approved` = '1' AND
                //                    `file_permission` = '0'
                //                    ORDER BY file_visted DESC $limiter";
                $query = $this->db->query("SELECT * FROM `file_info` WHERE
                    (`file_keyword` like '%$keyword%' OR
                     `file_name` like '%$keyword%') AND
                    `file_approved` = '1' AND
                    `file_permission` = '0'
                    ORDER BY file_visted DESC $limiter");
            }


            if ($query->num_rows() > 0) {
                $row0 = $query;
            }

            //Part II.

            if ($login) {
                $query1 = $this->db->query("SELECT * FROM `file_info` WHERE
                        `file_keyword_auto` like '%$keyword%' AND
                        `file_approved` = '1'
                        ORDER BY `file_visted` DESC");
            } else {
                if ($captcha) {
                    $limiter = '';
                } else {
                    $num_row = $query->num_rows();
                    $limiter = 'LIMIT ' . (3 - $num_row);
                }
                //                echo "SELECT * FROM `file_info` WHERE
                //                        `file_keyword_auto` like '%$keyword%' AND
                //                        `file_approved` = '1' AND
                //                        `file_permission` = '0'
                //                        ORDER BY `file_visted` DESC $limiter";
                $query1 = $this->db->query("SELECT * FROM `file_info` WHERE
                        `file_keyword_auto` like '%$keyword%' AND
                        `file_approved` = '1' AND
                        `file_permission` = '0'
                        ORDER BY `file_visted` DESC $limiter");
            }
            if ($query1->num_rows() > 0) {
                $row1 = $query1;
            }
            $data['row0'] = $row0;
            $data['row1'] = $row1;
            $this->load->view('web_result_view', $data);
        } else {
            $query = $this->db->query("SELECT * FROM `image_info` WHERE
                        `key` like '%$keyword%' AND
                        `approved` = '1' AND `isknown` = 1
                        ORDER BY `visted` DESC");
            $data['img_result'] = $query;
            $this->load->view('image_result_view', $data);
        }


    }

    public function image()
    {
        $_css = '<link href="' . base_url() . 'css/image.css" rel="stylesheet" type="text/css" />';
        $_title = 'Image Search';

        $data['main_content'] = 'image_view';
        $data['h_data']['page_title'] = $_title;
        $data['h_data']['_css'] = $_css;
        $this->load->view('includes/template', $data);
    }

    public function stats()
    {
        $data['m_data']['file_query'] =
                $this->db->query('SELECT * FROM db.file_info ORDER BY file_visted DESC LIMIT 20');
        $data['m_data']['user_query'] =
                $this->db->query('SELECT username,point FROM db.user_info ORDER BY point DESC LIMIT 20');
        $data['m_data']['image_query'] =
                $this->db->query('SELECT * FROM `image_info` ORDER BY visted DESC LIMIT 20');

        $_css = '<link href="' . base_url() . 'css/stats.css" rel="stylesheet" type="text/css" />';
        $_title = 'Statistics';

        $data['main_content'] = 'stats_view';
        $data['h_data']['page_title'] = $_title;
        $data['h_data']['_css'] = $_css;
        $this->load->view('includes/template', $data);
    }

    public function show_msg()
    {
        $username = $this->session->userdata('username');
        $msg_query = $this->db->
                query("SELECT * FROM `message` WHERE `to_user` = '$username' AND `read` = 0;");
        $data['msg_query'] = $msg_query;

        $this->load->view('pop_msg_view', $data);
    }

    public function close_msg()
    {
        if ($this->input->post('read') == 1) {
            $username = $this->session->userdata('username');
            $this->db->query("UPDATE `message` SET `read` = 1 WHERE `to_user` = '$username' AND `read` = 0");
        }
        echo 'DONE';
    }

    public function img()
    {
        $img_perm_query = $this->db->query("SELECT * FROM image_info WHERE `isknown` = 1 AND `approved` = 1");
        if ($img_perm_query->num_rows() > 0) {
            $row = $img_perm_query->row(rand(0, $img_perm_query->num_rows() - 1));
            $img_perm_url = $row->dir;
            $img_perm_key = $row->key;
        } else {
            die('No known image found in database.');
        }

        $img_temp_query = $this->db->query("SELECT * FROM image_info WHERE `isknown` = 0 AND `approved` = 1");
        if ($img_temp_query->num_rows() > 0) {
            $row = $img_temp_query->row(rand(0, $img_temp_query->num_rows() - 1));
            $img_temp_url = $row->dir;
            $img_temp_id = $row->id;
        } else {
            die('No known image found in database.');
        }

        $data['img_perm_url'] = $img_perm_url;
        $data['img_perm_key'] = $img_perm_key;
        $data['img_temp_url'] = $img_temp_url;
        $data['img_temp_id'] = $img_temp_id;
        $data['side'] = rand(0, 1);

        $this->load->view('img_view', $data);
    }

    public function validate_captcha()
    {
        $left = $this->input->post('left');
        $right = $this->input->post('right');
        $side = $this->input->post('side');
        $word = $this->input->post('word');
        $id = $this->input->post('temp_id');

        if (($side == 0 && $left == $word) || ($side == 1 && $right == $word)) {
            $temp_word = ($side) ? $left : $right;
            echo $this->save_captcha($id, $temp_word);
        } else {
            echo('Failed,Please Retry!<br/>');
        }
    }

    private function save_captcha($id, $temp_word)
    {
        $this->session->set_userdata(array('pass_cap' => TRUE));

        $username = $this->session->userdata('username');
        if (!empty($username)) {
            $query = $this->db->query("SELECT * FROM `image_key` WHERE `image_id` = '$id' AND `key` = '$temp_word'  LIMIT 1");
            if ($query->num_rows() > 0) //If it is not a new key for the image.
            {
                $row = $query->row();
                $init = $row->init;
                $key_id = $row->id;
                if ($row->vote >= 2) { //We have got enough votes.
                    //Set image is know and add permanent keyword
                    $this->db->query("UPDATE `image_info` SET `key` = '$temp_word',`isknown` = 1 WHERE `id`='$id' LIMIT 1");
                    //Delete all temp keys
                    $this->db->query("DELETE FROM `image_key` WHERE `image_id`= '$id'");
                    //+0.2 point to user who started this key.
                    $this->db->query("UPDATE `user_info` SET `point` = `point`+0.2 WHERE `username` = '$init' LIMIT 1");
                } else {
                    $this->db->query("UPDATE `image_key` SET `vote` = `vote`+1 WHERE `id`= '$key_id' LIMIT 1");
                }
            } else {
                $this->db->insert('image_key', array('image_id' => $id, 'key' => $temp_word, 'vote' => 1, 'init' => $username));
            }
        }
        $return = 'Passed!<br/>' . form_button('', 'Close', 'onclick="location.reload()"');
        return $return;
    }

    public function submit_complain()
    {
        $to = $this->uri->segment(3);
        $touser = $this->uri->segment(4);

        if (empty($to) || empty($touser)) {
            die('Submit complain failed. User or file not found.');
        } else {
            $insertion = array(
                'to' => $to,
                'to_user' => $touser,
                'read' => 0,
                'content' => 'file name: ' . $to . ' has been complain by a user!'
            );
            $this->db->insert('complain', $insertion);
            if ($this->db->affected_rows()) {
                echo 'Complain successfully submitted';
            } else {
                die('Submit complain failed.');
            }
        }
    }

    public function show_file()
    {
        $type = $this->uri->segment(3);
        $name = $this->uri->segment(4);
        if (!empty($type)) {
            if ($type == 1) //file
                $this->db->query("UPDATE `file_info` SET `file_visted` =  `file_visted` + 1 WHERE `file_id` = '$name' LIMIT 1");
            else {
                $this->db->query("UPDATE `image_info` SET `visted` =  `visted` + 1 WHERE `id` = '$name' LIMIT 1");
            }
        }
        redirect($_GET['url']);
    }


}